package data;

import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import models.OutLinkModel;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;

public class OutLinkData {
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String prefix = "outlink_";
	
	public OutLinkData() {
		try {
			ObjectifyService.register(OutLinkModel.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           //e.printStackTrace();
        }
		
        ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	public void insert(OutLinkModel outlink) {
		if (cache != null) {
			cache.put(prefix + outlink.getDomain(), outlink);
		}
		ofy.put(outlink);
	}
	
	public OutLinkModel get(String domain) {
		OutLinkModel outlink = new OutLinkModel();
		if (cache != null && cache.containsKey(prefix + domain)) {
			outlink = (OutLinkModel) cache.get(prefix + domain);
		} else {
			try {
				outlink = ofy.get(new Key<OutLinkModel>(OutLinkModel.class, domain));
				cache.put(prefix + domain, outlink);
			} catch (Exception e) {
				outlink = null;
			}
		}
		return outlink;
	}
	
	public void add(String domain, List<String> links) {
		OutLinkModel outlink = new OutLinkModel();
		for (int i = 0; i < links.size(); i++) {
			String name = links.get(i).replaceAll("(http|https)+://(www.)*", "");
			outlink = get(name);
			if (outlink == null) {
				outlink = new OutLinkModel();
				outlink.setDomain(name);
			}
			
			List<String> domains = outlink.getDomains(); 
			if (!domains.contains(domain)) {
				domains.add(domain);
				outlink.setDomains(domains);
				if (cache != null) {
					cache.put(prefix + outlink.getDomain(), outlink);
				}
				insert(outlink);
			}
		}
	}
	
	public void delete(OutLinkModel outlink) {
		if (cache != null && cache.containsKey(prefix + outlink.getDomain())) {
			cache.remove(prefix + outlink.getDomain());
		}
		ofy.delete(outlink);
	}
}
